<template>
  <div class="xxl-out-excel">
    <el-button :loading="isLoading" @click="goToOutExcel">导出</el-button>
  </div>
</template>

<script>
/**
 * exceljs的使用：
 *    npm i exceljs
 *    npm install -S file-saver
 */
/**
 * npm install -S xlsx
 * npm install -D script-loader
 * 这两个库应该可以不用的吧
 */
export default {
  name: "xxl-out-excel",
  props: {
    bookType: {
      type: String,
      default: "xlsx",
    },
    sheetnames: {
      type: Array,
      default: () => {
        return ["sheet"];
      },
    },
    filename: {
      type: String,
      default: "表格",
    },
    exportList: {
      type: Array,
      default: () => {
        return [];
      },
    },

    columnDefs: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      isLoading: false,
    };
  },
  methods: {
    /**
     * 点击导出按钮
     */
    async goToOutExcel() {
      try {
        //通过外部的条件判断是否可以导出
        //  this.$emit("on-out-begin");
        let exportStatus = true;
        if (this.$listeners[`on-out-begin`]) {
          exportStatus = await this.$listeners[`on-out-begin`]();
        }
        if (!exportStatus) {
          return;
        }
        this.isLoading = true;
        import("./Export2ExcelJs").then(async (excel) => {
          const params = this.getParams();
          await excel.export_json_to_excel_sheet(params);
          this.$emit("on-out-succeed");
          this.isLoading = false;
        });
      } catch (e) {
        console.log('导出异常报错：'+e)
        this.isLoading = false;
      }
    },
    /**
     * 获取入参
     */
    getParams() {
      const datas = [];
      for (let i = 0; i < this.columnDefs.length; i++) {
        //对应表头的列key
        const filterVal = this.columnDefs[i].map((val) => {
          return val.field;
        });
        //到出的数据
        const list = this.exportList[i];
        const data = this.formatJson(filterVal, list);
        datas.push(data);
      }

      return {
        headers: this.columnDefs,
        datas: datas,
        sheetnames: this.sheetnames,
        filename: this.filename, //导出的文件名称
        bookType: this.bookType,
      };
    },
    /**
     * 通过key找到data数据中对应的数据
     * 生成二维数组
     * @param {*} filterVal key值数组
     * @param {*} jsonData  表格数据
     */
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          return v[j];
        })
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.xxl-out-excel{
  display: inline-block;
}
</style>

